<?php

namespace App\Http\Controllers\User;

use App\Exceptions\OperateFailedException;
use App\Exceptions\ParamValidateFailedException;
use App\Http\Controllers\Controller;
use App\Http\Middleware\isAdmin;
use App\Models\Message;
use App\Models\Order;
use App\Models\User;
use function Composer\Autoload\includeFile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Overtrue\LaravelPinyin\Facades\Pinyin;
use App\Service\SmsService;

class UserController extends Controller
{
    public function __construct(){
        $this->middleware('auth:api')->except('destroy');
    }

    /* 获取用户信息
     *
     * @param openid
     * @return app\Models\User
     */
    public function show(User $user){
        $client_user = Auth::id();
        $check_friend = DB::table('friends')
                ->where('user_id',$client_user)
                ->where('friend_id',$user->id)
                ->get()->toArray();
        $flag = false;
        //判断是否为好友关系
        if (!empty($check_friend)){
            $flag = true;
        }
        $data = ['flag'=>$flag,'user_info'=>$user];
        return $this->responseSuccess($data);
    }

    /* 编辑用户信息
     *
     * @param openid
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request, User $user){
        //Lack Data Validation currently
        $this->authorize('update',$user);

        $validator = Validator::make($request->all(),
            [   'number' => 'required',
                'college'=> 'required',
                'name' => 'required',
                'phone' => 'required',
                'gender' => 'required'
            ]
        );
        if ($validator->fails()){
            return $this->responseParamValidateFailed($validator->errors());
        }

        $user = Auth::user();
        try{
            if ($user->phone == $request->get('phone')){
                $user->uid = $request->get('number');
                $user->unit = $request->get('college');
                $user->real_name = $request->get('name');
                $user->sex = $request->get('gender');
                $user->save();
            }else{
                throw new OperateFailedException();
            }

        }catch (\Exception $exception){
            return $this->responseOperateFailed();
        }
        return $this->responseSuccess();
    }
    /* 删除用户
     *
     * @param openid
     * @return \Illuminate\Http\JsonResponse
     * @throw OperateFailedException
     */
    public function destroy(User $user){
        $orders = $user->orders;
        foreach ($orders as $order){
            $order->delete();
        }

        $orders_receive = $user->orders_receive;
        foreach ($orders_receive as $order){
            $order->receiver = '';
            !($order->status == Order::ORDER_STATUS_RUNNING) ?: $order->status = Order::ORDER_STATUS_PUBLISHED;
        }

        $user->delete();
        return $this->responseSuccess();
    }


    /* 添加好友
     *
     * @param openid
     * @return \Illuminate\Http\JsonResponse
     * @throw OperateFailedException
     */
    public function follow(User $friend){
        $host = Auth::user();
//        $this->authorize('selfDone', $friend);
        DB::beginTransaction();
        try{
            $host->follow($friend->id);
            $friend->follow($host->id);
        }catch (\Exception $exception){
            throw new OperateFailedException();
        }
        DB::commit();
        return $this->responseSuccess();
    }

    /* 删除好友
     *
     * @param openid
     * @return \Illuminate\Http\JsonResponse
     * @throw OperateFailedException
     */
    public function unfollow(User $friend){
        $host = Auth::user();
        DB::beginTransaction();
        try{
            $host->unfollow($friend->id);
            $friend->unfollow($host->id);
        }catch (\Exception $exception){
            throw new OperateFailedException();
        }
        DB::commit();
        return $this->responseSuccess();
    }

    /* 好友列表
     *
     * @return app\Models\User
     */
    public function friendsList(){
        $user = Auth::user();
        $friends = $user->friends;
        foreach ($friends as $friend){
            $name = $friend->name;
            $letter = substr(strtoupper(Pinyin::abbr($name)),0,1);
            $friend->letter = $letter;
        }
        $friends = $friends->sortBy('letter')->groupBy('letter');
        return array($friends);
    }

    /* 消息列表
     *
     * @return app\Models\User
     */
    public function messageList(){
        $user = Auth::user();
        $openID = $user->openID;
        $messages = Message::where('from_id',$openID)->orWhere('to_id',$openID)
            ->latest()->get();
        $users_id = [];
        $contents = [];
        foreach ($messages as $message){
            $user_id = ($openID==$message->from_id) ? $message->to_id : $message->from_id;
            if (!in_array($user_id,$users_id)){
                array_push($users_id, $user_id);
                array_push($contents, ['content'=>$message->content, 'created_at'=>$message->created_at]);
            }
        }

        $users = [];
        $i = 0;
        foreach ($users_id as $user_id){
            try{
                $user = User::getInfoByOpenid($user_id)->toArray();
                $user['content'] = $contents[$i]['content'];
                $user['created_at'] = $contents[$i++]['created_at'];
                array_push($users,$user);
            }catch (\Exception $exception){
                throw new OperateFailedException($exception->getMessage());
            }
        }

        return $this->responseSuccess($users);

    }

    /**
     * 获取验证码
     * @param Request $request
     * @return string
     * @throws ParamValidateFailedException
     * @throws App\Exceptions\OperateFailedException
     */
    public function getCode(Request $request){
        $req = $request->all();
        $validator = Validator::make($req,['phone' => 'required']);
        if ($validator->fails()){
            throw new ParamValidateFailedException($validator);
        }
        $phone = $req['phone'];
        $code = SmsService::getCode($phone);
        return $this->responseSuccess($code);
    }

    /**
     * 验证短信验证码
     * @param Request $request
     * @return string
     * @throws OperateFailedException
     * @throws ParamValidateFailedException
     * @throws App\Exceptions\ResourceNotFoundException
     */
    public function Verify(Request $request){
        $req = $request->all();
        $validator = Validator::make($req,[
            'phone' => 'required|unique:users',
            'code' => 'required',
        ]);
        if ($validator->fails()){
            throw new ParamValidateFailedException($validator);
        }
        $phone = $req['phone'];
        $frontCode = $req['code'];
        $backCode=SmsService::verifyCode($phone,$frontCode);

        try{
            $user = Auth::user();
            $user->phone = $phone;
            $user->save();
        }catch (\Exception $exception){
            throw new OperateFailedException("手机绑定失败，请重试");
        }

        return $this->responseSuccess($backCode);
    }
}
